package cn.da.shuai.cool.security.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

public class SecurityUtil {

    public static UserDetails getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                return (UserDetails) principal;
            }
        }

        return null;
    }

    public static String getCurrentUsername() {
        UserDetails currentUser = getCurrentUser();
        return currentUser == null ? null : currentUser.getUsername();
    }

    public static Collection<? extends GrantedAuthority> getCurrentAuthority() {
        UserDetails currentUser = getCurrentUser();
        return currentUser == null ? List.of() : currentUser.getAuthorities();
    }
}
